﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Mvc.JQueryValidation;

namespace System.Web.Mvc
{
	public static class JQueryValidationExtension
	{
		public static string EnableJQueryValidation(this HtmlHelper htmlHelper)
		{
			var result = new StringBuilder();
			if (htmlHelper.ViewData["JQueryValidators"] != null)
			{
				var forms = (ValidateFormAttribute[])htmlHelper.ViewData["JQueryValidators"];
				if (forms.Length > 0)
				{
					result.Append("<script type=\"text/javascript\">");
					forms.ForEach(f => ProcessForm(f, result));
					result.Append("</script>");

				}
			}
			return result.ToString();
		}

		private static void ProcessForm(ValidateFormAttribute form, StringBuilder result)
		{
			if (form.Validators.Length > 0)
			{
				result.Append(String.Format(@"$(function ()
				{{
					$(""#{0}"").validate(
					{{", form.FormID));
				var fieldValidators = form.Validators.GroupBy(v => v.FieldName).ToList();
				ProcessRules(fieldValidators, result);
				result.Append(",");
				ProcessMessages(fieldValidators, result);
				result.Append("});});");
			}
		}

		private static void ProcessRules(List<IGrouping<string, ValidatorAttribute>> fieldValidators, StringBuilder result)
		{
			result.Append("rules:{");

			var groupSeparator = String.Empty;
			foreach (var group in fieldValidators)
			{
				var fieldName = group.Key;
				result.Append(groupSeparator);
				result.Append(fieldName).Append(@":
							{");

				var validatorSeparator = String.Empty;
				foreach (var validator in group)
				{
					result.Append(validatorSeparator);
					result.Append(validator.JQueryRule);
					validatorSeparator = ",";
				}

				result.Append("}");
				groupSeparator = ",";
			}

			result.Append("}");
		}

		private static void ProcessMessages(List<IGrouping<string, ValidatorAttribute>> fieldValidators, StringBuilder result)
		{
			result.Append("messages:{");

			var groupSeparator = String.Empty;
			foreach (var group in fieldValidators)
			{
				var fieldName = group.Key;
				result.Append(groupSeparator);
				result.Append(fieldName).Append(@":
							{");

				var validatorSeparator = String.Empty;
				foreach (var validator in group)
				{
					result.Append(validatorSeparator);
					result.Append(validator.JQueryRuleErrorMessage);
					validatorSeparator = ",";
				}

				result.Append("}");
				groupSeparator = ",";
			}

			result.Append("}");
		}
	}
}